package com.hmall.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Http;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.function.Consumer;
import java.util.function.Predicate;

//让AuthProperties上的@ConfigurationProperties生效
@EnableConfigurationProperties(AuthProperties.class)
@Component
public class AuthGlobalFilter implements GlobalFilter {

    @Autowired
    private AuthProperties authProperties;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private JwtTool jwtTool;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request和response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2.获取请求路径
        String path = request.getURI().getPath();
        //多个可以配置的地址
        boolean bo = authProperties.getExcludePaths()
                .stream()
                .anyMatch(url -> antPathMatcher.match(url,path));

        if (bo){
            //3.判断路径是否不需要对令牌进行校验，如果不需要，直接放行(/users/login)
            return chain.filter(exchange);
        }
        //4.需要拦截校验，获取请求头中的令牌
        String token = request.getHeaders().getFirst("authorization");
        // 5.对令牌进行校验
        Long userId=null;
        try {
            userId= jwtTool.parseToken(token);
        } catch (Exception e) {
        // 6.校验不通过，执行拦截操作
            //消息类型 application/json;charset=utf-8
            //响应状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //响应JSON类型
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response.writeWith(Mono.just(response.bufferFactory().wrap("{\"msg\":\"请先登录！\"}".getBytes(StandardCharsets.UTF_8))));
        }
        // 7.解析令牌，获取用户ID 把用户ID放到请求中
        String userInfo = userId.toString();
        request.mutate().headers(httpHeaders -> httpHeaders.set("user-info",userInfo));

        //8. 放行->Http请求
        return chain.filter(exchange);
    }
}
